//
//  NSString+PP.m
//  pickpic
//
//  Created by Jinxiao on 10/7/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "NSString+PP.h"

@implementation NSString (PP)

- (NSString *)thumbnailStringByConstrainingToWidth:(CGFloat)width {
    return [NSString stringWithFormat:@"%@?imageView2/3/w/%li", self, (long)width];
}

- (NSString *)thumbnailStringByConstrainingToHeight:(CGFloat)height {
    return [NSString stringWithFormat:@"%@?imageView2/3/h/%li", self, (long)height];
}

- (void)applyToImageView:(UIImageView *)imageView {
    [self applyToImageView:imageView placeholder:nil];
}

- (void)applyToImageView:(UIImageView *)imageView placeholder:(UIImage *)placeholder {
    [self applyToImageView:imageView placeholder:placeholder completion:nil];
}

- (void)applyToImageView:(UIImageView *)imageView placeholder:(UIImage *)placeholder completion:(void (^)(void))completion {
    [self applyToImageView:imageView placeholder:placeholder progressive:nil completion:completion];
}

- (void)applyToImageView:(UIImageView *)imageView placeholder:(UIImage *)placeholder progressive:(void (^)(double))progressive completion:(void (^)(void))completion {
    NSString *urlString = self;

    urlString = [urlString thumbnailStringByConstrainingToWidth:imageView.width*2.6];

    [imageView sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:placeholder options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        double progress = 1.0*receivedSize/expectedSize;
        !progressive ?: progressive(progress);
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        !completion ?: completion();
    }];
}

- (void)applyToImageView:(UIImageView *)imageView placeholder:(UIImage *)placeholder progressive:(void (^)(double))progressive errorCompletion:(void (^)(NSError *error))errorCompletion {
    NSString *urlString = self;

    urlString = [urlString thumbnailStringByConstrainingToWidth:imageView.width*2.6];

    [imageView sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:placeholder options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        double progress = 1.0*receivedSize/expectedSize;
        !progressive ?: progressive(progress);
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        !errorCompletion ?: errorCompletion(error);
    }];
}

@end
